import axios from "axios"
import { ElMessage } from 'element-plus'
import userUserStore from "@/store/modules/user"



const request = axios.create({
  // 基础路径  api
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000  //超时时间
})

request.interceptors.request.use((config) => {
  const userStore = userUserStore()
  config.headers.token = userStore.token
  // 请求拦截下来了,返回回去.
  return config;
})

request.interceptors.response.use((response) => {
  // 成功的回调。

  return response.data;
}, (error) => {
  // 状态码400 404 500错误
  let msg = ""
  console.log(error)
  let code;
  try {
    code = error.response.code
  } catch (error) {
    code = 0;
  }


  switch (code) {
    case 401:
      msg = "token过期"
      break;
    case 403:
      msg = "无权限访问";
      break;

    case 404:
      msg = "页面不存在";
      break;
    case 500:
      msg = "服务器出现问题";
      break;

    default:
      msg = "网络错误";
  }
  ElMessage({
    showClose: true,
    message: msg,
    type: 'error',
  })
  return Promise.reject(error);
  // 失败的回调
})


export default request;